package com.elong.businesstravel.modules.home;

import org.apache.http.Header;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.utils.CoordinateConversion;
import com.android.support.jhf.utils.ImageUtil;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BaiduMap.OnMapLongClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baidusdk.map.BaiduMapView.LocationOverlayDispatchTap;
import com.elong.businesstravel.base.utils.SettingsUtils;
import com.elong.businesstravel.entitys.Hotel;
import com.elong.businesstravel.entitys.HotelDocs;
import com.elong.businesstravel.entitys.HotelNameSearchResult;
import com.elong.businesstravel.entitys.HotelSearchCondition;
import com.elong.businesstravel.entitys.MyGeoPoint;
import com.elong.businesstravel.modules.home.baseactivity.BaseHotelResultActivity;

/**
 * 酒店搜索结果地图页
 * 
 * @author lenovo
 * 
 */
public class HotelSearchResultMapActivity extends BaseHotelResultActivity {

	private InfoWindow mInfoWindow;
	private BitmapDescriptor mMarker;

	// UI相关
	private Bitmap mPhoto;

	/** true表示抵扣列表跳转到map界面 */
	private boolean mPrepaidFlag = false;
	/** true显示浮窗，false隐藏浮窗 */
	private boolean mIsShow = false;
	/** true长按，false不长按 */
	private boolean mIsLongClick = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hotel_search_map_result);

		init();
	}

	@Override
	protected void init() {
		if (null == mSavedInstanceState) {
			mCurrentHotelSearchCondition = (HotelSearchCondition) getIntent()
					.getSerializableExtra("HotelSearchCondition");
			if (-1 == SettingsUtils.getHotelFull(mContext)) {
				mCurrentHotelSearchCondition.isfull = 1;
			} else {
				mCurrentHotelSearchCondition.isfull = SettingsUtils
						.getHotelFull(mContext);
			}
			mHotel = (Hotel) getIntent().getSerializableExtra("Hotel");
			mSortByDistance = getIntent().getBooleanExtra("SortByDistance",
					false);
			mPrepaidFlag = getIntent().getBooleanExtra("prepaid", false);
			mDestGeoPoint = (MyGeoPoint) getIntent().getSerializableExtra(
					"DestGeoPoint");
		}

		mLongClickTextView = (TextView) findViewById(R.id.longClickTextView);

		super.init();

		mMapView = (MapView) findViewById(R.id.mapView);
		initBaiduMap(mMapView);

		mMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_gcoding);

		setListener();

		mBaiduMap.setOnMapLoadedCallback(new OnMapLoadedCallback() {

			@Override
			public void onMapLoaded() {
				mHandler.sendMessage(mHandler.obtainMessage(0, mSortByDistance));
			}
		});

		mPhoto = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.ic_marka);

		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker arg0) {

				if (null == arg0) {
					return true;
				}
				String hotelName = arg0.getTitle();
				LatLng geoPoint = arg0.getPosition();
				String hotelAddress = null;
				int index = 0;
				if (null != arg0.getExtraInfo()) {
					hotelAddress = arg0.getExtraInfo().getString("snippet");
					index = arg0.getExtraInfo().getInt("index");
				}

				mShowPopupOverlay.hotelName = hotelName;
				mShowPopupOverlay.hotelAddress = hotelAddress;
				mShowPopupOverlay.p1 = geoPoint;
				mShowPopupOverlay.index = index;
				mShowPopupFlag = true;
				showPopupOverlay(mShowPopupOverlay);

				return false;
			}
		});

		mBaiduMap.setOnMapClickListener(new OnMapClickListener() {

			@Override
			public boolean onMapPoiClick(MapPoi arg0) {
				return false;
			}

			@Override
			public void onMapClick(LatLng arg0) {
				if (null != mBaiduMap) {
					mIsShow = false;
					mBaiduMap.hideInfoWindow();
				}
			}
		});

		mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {

			@Override
			public void onMapStatusChangeStart(MapStatus arg0) {
				if (null != mBaiduMap) {
					mBaiduMap.hideInfoWindow();
				}
			}

			@Override
			public void onMapStatusChangeFinish(MapStatus arg0) {

				if (null != mBaiduMap && mIsShow) {
					showPopupOverlay(mShowPopupOverlay);
				}
			}

			@Override
			public void onMapStatusChange(MapStatus arg0) {
			}
		});

		mBaiduMap.setOnMapLongClickListener(new OnMapLongClickListener() {

			@Override
			public void onMapLongClick(LatLng arg0) {

				mIsLongClick = true;

				mDestGeoPoint = new MyGeoPoint(arg0);

				double[] lngLat = CoordinateConversion.bd2gg(arg0.latitude,
						arg0.longitude);

				getHotlList(false, lngLat[1], lngLat[0]);

			}
		});

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		mSortByDistance = getIntent().getBooleanExtra("SortByDistance", false);
		// mHandler.sendMessage(mHandler.obtainMessage(0, mSortByDistance));
		mBaiduMap.setOnMapLoadedCallback(new OnMapLoadedCallback() {

			@Override
			public void onMapLoaded() {
				mHandler.sendMessage(mHandler.obtainMessage(0, mSortByDistance));
			}
		});
	}

	@Override
	protected void setListener() {
		mBaiduMapView
				.setLocationOverlayDispatchTap(new LocationOverlayDispatchTap() {

					@Override
					public boolean dispatchTap() {
						// 处理点击事件,弹出泡泡
						return true;
					}
				});

		Button locButton = (Button) findViewById(R.id.locButton);
		locButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				baiduLocation();
			}
		});

		Button moreButton = (Button) findViewById(R.id.moreButton);
		moreButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				getHotelList(true);

			}
		});

		super.setListener();
	}

	@Override
	protected void getLocationSucceed(BDLocation location) {
		double[] lngLat = CoordinateConversion.bd2gg(location.getLatitude(),
				location.getLongitude());

		getHotlList(false, lngLat[1], lngLat[0]);
	}
	
	@Override
	protected void updateHotelDate(boolean sortByDistance) {
		// 更新地图数据
		mHandler.sendMessage(mHandler.obtainMessage(0, sortByDistance));
	}

	/**
	 * 长按显示在地图上的
	 * @param p1
	 * @param hotelName
	 */
	private void addOverlay(MyGeoPoint p1, String hotelName) {

		OverlayOptions ooA = new MarkerOptions().position(p1.getLatLng())
				.icon(mMarker).title(hotelName).zIndex(9).draggable(false);
		mBaiduMap.addOverlay(ooA);

//		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(p1.getLatLng());
//		mBaiduMapView.getBaiduMap().animateMapStatus(u);

	}

	private void addOverlay(HotelNameSearchResult hotelNameSearchResult) {
		double baiduLat = 0;
		double baiduLng = 0;
		if (null != mApplication.mBdLocation) {
			baiduLat = mApplication.mBdLocation.getLatitude();
			baiduLng = mApplication.mBdLocation.getLongitude();
		}
		try {
			double googleLat = Double
					.parseDouble(hotelNameSearchResult.googlelat);
			double googleLng = Double
					.parseDouble(hotelNameSearchResult.googlelng);
			double[] lngLat = CoordinateConversion.gg2bd(googleLat, googleLng);
			baiduLat = lngLat[1];
			baiduLng = lngLat[0];
		} catch (Exception e) {
		}

		LatLng p1 = new LatLng(baiduLat, baiduLng);

		OverlayOptions ooA = new MarkerOptions().position(p1).icon(mMarker)
				.title(hotelNameSearchResult.hotelName).zIndex(9)
				.draggable(false);
		mBaiduMap.addOverlay(ooA);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(p1);
		mBaiduMapView.getBaiduMap().animateMapStatus(u);

	}
	
	@Override
	protected void onFailure(int statusCode, Header[] headers,
			byte[] responseBody, Throwable error) {
		mIsLongClick = false;
	}

	private void addOverlay(HotelDocs hotelDocs, final int index) {

		double baiduLat = 0;
		double baiduLng = 0;
		if (null != mApplication.mBdLocation) {
			baiduLat = mApplication.mBdLocation.getLatitude();
			baiduLng = mApplication.mBdLocation.getLongitude();
		}
		try {
			double googleLat = Double
					.parseDouble(hotelDocs.latlng_0_coordinate);
			double googleLng = Double
					.parseDouble(hotelDocs.latlng_1_coordinate);
			double[] lngLat = CoordinateConversion.gg2bd(googleLat, googleLng);
			baiduLat = lngLat[1];
			baiduLng = lngLat[0];
		} catch (Exception e) {
		}

		String price = "￥" + hotelDocs.minPrice;

		LatLng p1 = new LatLng(baiduLat, baiduLng);

		Bundle bundle = new Bundle();
		bundle.putString("snippet", hotelDocs.hotelAddress);
		bundle.putInt("index", index);
		OverlayOptions ooA = new MarkerOptions()
				.position(p1)
				.icon(BitmapDescriptorFactory.fromBitmap(ImageUtil
						.drawable2Bitmap(ImageUtil.watermark(mPhoto, price,
								23.0f, android.graphics.Color.WHITE))))
				.title(hotelDocs.hotelName).extraInfo(bundle).zIndex(9)
				.draggable(false);
		mBaiduMap.addOverlay(ooA);

		if (0 == index) {
			if (!mIsLongClick) {
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(p1);
				mBaiduMapView.getBaiduMap().animateMapStatus(u);
				
			}
			mIsLongClick = false;
			mShowPopupOverlay.hotelName = hotelDocs.hotelName;
			mShowPopupOverlay.hotelAddress = hotelDocs.hotelAddress;
			mShowPopupOverlay.p1 = p1;
			mShowPopupOverlay.index = 0;
			mShowPopupFlag = true;
			showPopupOverlay(mShowPopupOverlay);
		}
	}

	@Override
	protected void titleRightOnClick(String textString) {
		Intent intent = new Intent();
		if (LIST.equals(textString)) {
			if (mPrepaidFlag) {
				// 跳转到抵扣酒店列表
				intent.setClass(mContext,
						PrepaidHotelSearchResultActivity.class);
			} else {
				// 跳转到所有酒店列表
				intent.setClass(mContext, HotelSearchResultActivity.class);
			}
			intent.putExtra("activityTag", MAP);
			intent.putExtra("HotelSearchCondition",
					mCurrentHotelSearchCondition);
			intent.putExtra("sort", mHotelSort);
			intent.putExtra("Hotel", mHotel);
			intent.putExtra("prepaid", mPrepaidFlag);
			intent.putExtra("SortByDistance", mSortByDistance);
			intent.putExtra("DestGeoPoint", mDestGeoPoint);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

		}
		startActivityForResult(intent, 4);
	}

	@Override
	protected void titleLeftOnClick(String textString) {
		Intent intent = new Intent();
		if (LIST.equals(textString)) {
			if (mPrepaidFlag) {
				// 跳转到抵扣酒店列表
				intent.setClass(mContext,
						PrepaidHotelSearchResultActivity.class);
			} else {
				// 跳转到所有酒店列表
				intent.setClass(mContext, HotelSearchResultActivity.class);
			}
			intent.putExtra("activityTag", MAP);
			intent.putExtra("HotelSearchCondition",
					mCurrentHotelSearchCondition);
			intent.putExtra("sort", mHotelSort);
			intent.putExtra("Hotel", mHotel);
			intent.putExtra("SortByDistance", mSortByDistance);
			intent.putExtra("DestGeoPoint", mDestGeoPoint);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		}
		startActivityForResult(intent, 4);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		default:
			break;
		}
	}

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0: {
				if (null != hotelNameSearchResult) {
					mHotelNameTextView.setVisibility(View.VISIBLE);
					mHotelNameLayout.setVisibility(View.VISIBLE);

					String nameString = hotelNameSearchResult.hotelName;
					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.districtsname;
					}

					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.bussinename;
					}

					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.name;
					}

					if (TextUtils.isEmpty(nameString)) {
						nameString = hotelNameSearchResult.shortname;
					}
					mHotelNameTextView.setText(nameString);
					// mSearchTextView.setVisibility(View.INVISIBLE);
					mSearchTopLayout.setVisibility(View.INVISIBLE);

				} else if (!TextUtils
						.isEmpty(mCurrentHotelSearchCondition.keyword)) {
					mHotelNameTextView.setVisibility(View.VISIBLE);
					mHotelNameLayout.setVisibility(View.VISIBLE);
					mHotelNameTextView
							.setText(mCurrentHotelSearchCondition.keyword);
					// mSearchTextView.setVisibility(View.INVISIBLE);
					mSearchTopLayout.setVisibility(View.INVISIBLE);
				} else {
					mHotelNameTextView.setVisibility(View.GONE);
					mHotelNameLayout.setVisibility(View.GONE);
					if ("".equals(mCurrentHotelSearchCondition.keyword)) {
						mHotelNameTextView
								.setText(mCurrentHotelSearchCondition.keyword);
					}
					// mSearchTextView.setVisibility(View.INVISIBLE);
					mSearchTopLayout.setVisibility(View.VISIBLE);
				}
				if (mBaiduMap != null) {
					mBaiduMap.hideInfoWindow();
					mIsShow = false;
				}

				mBaiduMap.clear();

//				if (null != hotelNameSearchResult
//						&& !TextUtils.isEmpty(hotelNameSearchResult.googlelat)
//						&& !TextUtils.isEmpty(hotelNameSearchResult.googlelng)
//						&& !TextUtils.isEmpty(hotelNameSearchResult.hotelName)) {
//					addOverlay(hotelNameSearchResult);
//				} else {
//
//				}

				if (mIsLongClick && "目的地"
						.equals(mCurrentHotelSearchCondition.mSearchConditionPoi.name)) {

					addOverlay(mDestGeoPoint, "目的地");
				}

				// mHotelSearchResultAdapter.notifyDataSetChanged();
				for (int i = 0; i < mHotel.mHotelDocs.size(); i++) {
					addOverlay(mHotel.mHotelDocs.get(i), i);
				}

				boolean sortByDistance = (Boolean) msg.obj;
				if (sortByDistance) {
					// 修改排序，按照距离排序
					if (-1 == mCurrentHotelSearchCondition.sorts) {
						mCurrentHotelSearchCondition.sorts = 4;
					}
					mHotelSort = mApplication.mHotelLocSorts;
				} else {
					// 默认排序
					// mCurrentHotelSearchCondition.sorts = 0;
					mHotelSort = mApplication.mHotelSorts;
				}

				break;
			}
			case 1: {
				break;
			}
			default:
				break;
			}
			return false;
		}
	});

	private void showPopupOverlay(ShowPopupOverlay showPopupOverlay) {
		final String hotelName = showPopupOverlay.hotelName;
		String hotelAddress = showPopupOverlay.hotelAddress;
		LatLng geoPoint = showPopupOverlay.p1;
		final int index = showPopupOverlay.index;

		View view = LayoutInflater.from(mContext).inflate(
				R.layout.view_popupoverlay, null);

		ViewGroup popupLayout = (ViewGroup) view.findViewById(R.id.popupLayout);

		popupLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!"目的地".equals(hotelName)) {
					Intent intent = new Intent(mContext,
							HotelDetailActivity.class);
					intent.putExtra("hotelDocs", mHotel.mHotelDocs.get(index));
					intent.putExtra("product",
							mCurrentHotelSearchCondition.product);
					startActivity(intent);
				}
			}
		});
		TextView hotelNameTextView = (TextView) view
				.findViewById(R.id.hotelNameTextView);
		hotelNameTextView.setText(hotelName);

		TextView hotelAddressTextView = (TextView) view
				.findViewById(R.id.hotelAddressTextView);
		if (null == hotelAddress) {
			hotelAddressTextView.setVisibility(View.GONE);
		} else {
			hotelAddressTextView.setVisibility(View.VISIBLE);
			hotelAddressTextView.setText(hotelAddress);
		}

		Button hotelInfoButton = (Button) view
				.findViewById(R.id.hotelInfoButton);
		hotelInfoButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});

		Point p = mBaiduMap.getProjection().toScreenLocation(geoPoint);
		p.y -= 20;
		LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);

		OnInfoWindowClickListener listener = new OnInfoWindowClickListener() {
			public void onInfoWindowClick() {
				if (!"目的地".equals(hotelName)) {
					Intent intent = new Intent(mContext,
							HotelDetailActivity.class);
					intent.putExtra("hotelDocs", mHotel.mHotelDocs.get(index));
					intent.putExtra("product",
							mCurrentHotelSearchCondition.product);
					startActivity(intent);
				}
			}
		};

		mInfoWindow = new InfoWindow(view, llInfo, listener);
		mBaiduMap.showInfoWindow(mInfoWindow);
		mIsShow = true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			titleLeftOnClick(mActivityTag);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
